package edu.xidian.cnmano.service.impl;

import edu.xidian.cnmano.dao.K8svaluesMapper;
import edu.xidian.cnmano.entities.nsorchestrate.K8svalues;
import edu.xidian.cnmano.entities.nsorchestrate.K8svaluesExample;
import edu.xidian.cnmano.entities.nsorchestrate.K8svaluesInFile;
import edu.xidian.cnmano.service.K8sValuesService;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.util.List;

/**
 * @author zhr
 * @date 2021/1/17-17:21
 */
@Service
public class K8sValuesServiceImpl implements K8sValuesService {
    @Resource
    private K8svaluesMapper k8svaluesMapper;

    @Override
    public List<K8svalues> listK8sValues() {
        K8svaluesExample example = new K8svaluesExample();
        return k8svaluesMapper.selectByExample(example);
    }

    @Override
    public String k8sValuesToFile(Integer id) {
        K8svalues k8svalues = k8svaluesMapper.selectByPrimaryKey(id);
        K8svaluesInFile k8svaluesInFile = new K8svaluesInFile(k8svalues.getName(), k8svalues.getDeploymentDescription(), k8svalues.getReplicas(),
                k8svalues.getBitrateRequirement(), k8svalues.getPodDescription(), k8svalues.getImageUrl(), k8svalues.getPortName(),
                k8svalues.getContainerPort(), k8svalues.getServicePort(), k8svalues.getL4protocol(), k8svalues.getRequestCpu(),
                k8svalues.getRequestMemory(), k8svalues.getCpuLimit(), k8svalues.getMemoryLimit(), k8svalues.getLocation(),
                k8svalues.getPodAffinity());
        Yaml yaml = new Yaml();
        String str = yaml.dumpAsMap(k8svaluesInFile);
        try {
            FileWriter fileWriter = new FileWriter("/home/k8s-mec/cnMANO/generatedValues/values"+id+".yaml");
            fileWriter.flush();
            fileWriter.write(str);
            fileWriter.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    @Override
    public K8svalues getK8sValuesById(Integer id) {
        return k8svaluesMapper.selectByPrimaryKey(id);
    }
}
